from itpay.core.agency.models import AccountStat
from itpay.core.user.const import UserLevel

NoneValue = object()


def create_stat(agency_id):
    AccountStat(account_id=agency_id).save()


def update_stat(agency_id, pay_types=None, month_orders_count=None, month_good_comments_count=None,
                support_auto_arrival=None, auto_arrival_min_level=None):
    assert agency_id > 0
    if pay_types:
        assert isinstance(pay_types, dict) or pay_types == NoneValue

    m_stat = _get_stat(agency_id)
    if pay_types:
        m_stat.pay_type_1_min_level = 0
        m_stat.pay_type_2_min_level = 0
        m_stat.pay_type_3_min_level = 0
        m_stat.pay_type_4_min_level = 0
        m_stat.pay_type_5_min_level = 0
        if pay_types == NoneValue:
            m_stat.pay_types = None
        else:
            m_stat.pay_types = list(pay_types.keys())
            for pay_type, min_level in pay_types.items():
                setattr(m_stat, 'pay_type_{}_min_level'.format(pay_type), min_level)
    if month_orders_count is not None:
        m_stat.month_orders_count = month_orders_count
    if month_good_comments_count is not None:
        m_stat.month_good_comments_count = month_good_comments_count
    if support_auto_arrival is not None:
        m_stat.support_auto_arrival = support_auto_arrival
        m_stat.auto_arrival_min_level = auto_arrival_min_level if auto_arrival_min_level is not None else UserLevel.LEVEL_0.value

    m_stat.save()


def get_stat(agency_id):
    return _get_stat(agency_id).to_dict()


def get_agency_min_user_level(agency_id):
    stat = get_stat(agency_id)
    return min(stat['pay_type_1_min_level'], stat['pay_type_2_min_level'], stat['pay_type_3_min_level'],
               stat['pay_type_4_min_level'], stat['pay_type_5_min_level'])


def _get_stat(agency_id):
    m_stat = AccountStat.objects.filter(account_id=agency_id).first()
    assert m_stat
    return m_stat
